import {ref, onMounted, onUnmounted, inject, reactive, nextTick} from 'vue';
import {useConfigStore} from '@/stores/config.js';
import {useUserStore} from '@/stores/user.js';
import {post} from "@/function/request/index.js";
import {ElNotification} from "element-plus";

function useModalMinix() {
  const {baseURL, menuList,industry, token, userInfo, config} = useUserStore();
  const submitLoading = ref(false);
  const loading = ref(false);
  const {baseDataMap} = useConfigStore();
  const formRef = ref();
  const form = reactive({});

  onMounted(() => {
  });

  onUnmounted(() => {
  });
  const closeModal = inject('closeModal');
  // 表单字段单独校验，用于解决类似附件上传后但校验未触发
  const formValidateField = function (key) {
    nextTick(() => {
      formRef.value.validateField(key)
    })
  }

  function saveForm(url, formData = form, closeFlag = true) {
    return new Promise((resolve, reject) => {
      console.log(formRef.value)
      formRef.value.validate(async (valid, fields) => {
        if (valid) {
          submitLoading.value = true;
          loading.value = true;
          try {
            let res = await post(url, formData || form);
            if (res.code === 200) {
              if (closeFlag) {
                ElNotification.success({
                  title: '提示',
                  message: '操作成功！',
                })
                closeModal();
              }
              resolve(res);
            } else {
              reject(res);
            }
          } catch (err) {
            reject(err);
          } finally {
            loading.value = false;
            submitLoading.value = false;
          }
        } else {
          ElNotification.error({
            title: "操作失败！",
            message: '请检查表单是否填项正确！'
          });
          reject(fields)
        }
      }).catch(err => {
        reject(err)
      })
    })
  }

  return {
    baseURL,
    config,
    baseDataMap,
    industry,
    menuList,
    token,
    saveForm,
    userInfo,
    loading,
    form,
    formRef,
    submitLoading,
    closeModal,
    formValidateField
  };
}

export default useModalMinix;
